package com.android.serialport;

import java.io.IOException;
import java.io.InputStream;

/**
 * @author Administrator
 * @date 2021/1/30
 */
public abstract class ReceiveThread extends Thread{
    private byte[] mReceiveBuffer;
    private InputStream mInputStream;
    public ReceiveThread(InputStream inputStream){
        mInputStream = inputStream;
        mReceiveBuffer = new byte[2048];
    }
    @Override
    public void run() {
        while (!isInterrupted()) {
            try {
                if (null == mInputStream) {
                    return;
                }
                int size = mInputStream.read(mReceiveBuffer);
                if (0 >= size) {
                    return;
                }
                byte[] receivedBytes = new byte[size];
                System.arraycopy(mReceiveBuffer, 0, receivedBytes, 0, size);
                onReceived(receivedBytes);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    public abstract void onReceived(byte[] bytes);

    /**
     * 释放
     */
    public void close() {
        interrupt();

        if (null != mInputStream) {
            try {
                mInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mInputStream = null;
        }
    }
}